package com.foxit.pdf2html5.web.controller;

import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foxit.pdf2html5.common.utils.URLConnectionHelper;
import com.foxit.pdf2html5.web.common.Config;
import com.foxit.pdf2html5.web.common.HttpConnectionManager;
import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudHttpKey;
import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudHttpState;
//import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudIterfaceImp;

import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudIterfaceImp;
import com.foxit.pdf2html5.web.common.Pager;
/*import com.foxit.webreader.common.ConfigConstans;
import com.foxit.webreader.common.intergration.BaseDocument;
import com.foxit.webreader.common.intergration.ICacheStoreProvider;
import com.foxit.webreader.common.intergration.IDocStore;
import com.foxit.webreader.common.intergration.ReaderAppContext;*/
import com.foxit.pdf2html5.web.common.DelFileOrDir;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;


@Controller
public class FileMgrController {
	private String xml_root = Config.HTML5EDITOR_XML_FILE_ROOT_STR_KEY;
	private String sSeparator = System.getProperties().getProperty("file.separator");
	
	
	@RequestMapping(value="/ListFile.do")  
	public void ListFile(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException
	{
		FoxitCloudIterfaceImp uploadFile = new FoxitCloudIterfaceImp();
		String sUserID = Config.FOXIT_USER_ID_KEY;
		HashMap tokenMap = uploadFile.getToken(sUserID);
		if (null == tokenMap)
		{
			return;
		}
		else
		{
			Double tokenRet = (Double)tokenMap.get(FoxitCloudHttpKey.RET);
			if(tokenRet != FoxitCloudHttpState.HTTP_SUCCESS){
				return;
			}
			String token = (String)tokenMap.get(FoxitCloudHttpKey.TOKEN);
			
			HashMap<String, Object> resultMap = new HashMap<String, Object>();
			String filePath = "/" ;
			//String filePath = "/userstorage/20140809/34ae0dc894a6625a499aeacffc1eb875-86b690b032be7861df5d0e2983e99d91190c12230";
			Gson gson = new Gson();
			String arrExt = "pdf";
			JsonObject postObj = new JsonObject();
			postObj.addProperty(FoxitCloudHttpKey.TOKEN, token);
			postObj.addProperty(FoxitCloudHttpKey.PATH, filePath);
			//postObj.addProperty(FoxitCloudHttpKey.EXTENSION, arrExt);
			//postObj.addProperty(FoxitCloudHttpKey.LIMIT, "");
			String sFileListUrl = Config.FOXIT_CLOUND_URSER_FILE_LIST_KEY;
			
			String sResult = URLConnectionHelper.sendPost(sFileListUrl, gson.toJson(postObj));
			
			if ("" != sResult)
			{
				resultMap = gson.fromJson(sResult.trim(), HashMap.class);
			}
			else
			{
				return;
			}
			
			String pageSize = request.getParameter("PAGE_SIZE");
			String currentPage = request.getParameter("CURRENT_PAGE");
			
			ArrayList<Object> list = (ArrayList<Object>)resultMap.get("list");
			List<Object> listmp = new ArrayList<Object>();
			int start = (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize);
			int end = start + Integer.parseInt(pageSize) > list.size() ? list.size() : start + Integer.parseInt(pageSize);
			
			int count = list.size();
			int totalNum = list.size();
			
			for (int i = start; i < end; ++ i)
			{
				
				HashMap<String, Object> map = (HashMap<String, Object>)list.get(i);
				
				String sFileName = (String) map.get("path");
				String name = sFileName.substring(1);
				Float sSize = Float.valueOf(map.get("size").toString());
				
				BigDecimal db = new BigDecimal(map.get("mtime").toString());
				String sModifyTime = db.toPlainString();
				Date date = new Date(Long.parseLong(sModifyTime));
				
				String id = (String)map.get("doc_id");
				
				
				JSONObject json = new JSONObject();
				try {
					json.put("DOC_NAME", name);
					json.put("DOC_VERSION", 1.0);
					json.put("USER", "me");
					json.put("DOC_SIZE", sSize);
					json.put("CREATETIME2", date);
					json.put("PK_PDF_DOC", id);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				listmp.add(json);
				//totalNum ++;
			}
			
			Map<String,Object> jsonmap = new HashMap<String, Object>();
			Map<String,Object> rootmap = new HashMap<String, Object>();
			jsonmap.clear();
			jsonmap.put(xml_root, listmp);
			Pager pager = new Pager(Integer.parseInt(pageSize), Integer.parseInt(currentPage));
			pager.setTotalRows(totalNum);
			JSONObject objectpager = new JSONObject(pager);
			jsonmap.put("pager", objectpager);
			rootmap.put("root", jsonmap);
			JSONObject object = new JSONObject(rootmap);
			System.out.println(object.toString());
			response.getWriter().write(object.toString());
			return;
		}
	}
	
	@RequestMapping( value = "/DelFile.do" )
	public void DelFile(HttpServletRequest request,HttpServletResponse response) throws IOException
	{

		boolean bResult = false;
		try {
			FoxitCloudIterfaceImp uploadFile = new FoxitCloudIterfaceImp();
			HashMap tokenMap = uploadFile.getToken(Config.FOXIT_USER_ID_KEY);
			Double tokenRet = (Double)tokenMap.get(FoxitCloudHttpKey.RET);
			if(tokenRet != FoxitCloudHttpState.HTTP_SUCCESS){
				return;
			}
			String token = (String)tokenMap.get(FoxitCloudHttpKey.TOKEN);
			
			if(token == null || "".equals(token)){
				return;
			}
			String sFileName = request.getParameter("docName");
			String sDocId = request.getParameter("id");
			
			
			String sDataPath = request.getSession().getServletContext().getRealPath("");
			String slocalBinFile = sDataPath + sSeparator + "WebReaderDocPath" + sSeparator + sDocId;
			
			bResult = deleteFileOnCloud(token, sFileName, sDocId);
			/*if (bResult)
			{
				//删除分布式系统上的文件
				ICacheStoreProvider cacheStoreProvider = ReaderAppContext.CacheStoreProvider();
				IDocStore docStore = ReaderAppContext.DocStore();
				BaseDocument baseDoc = (BaseDocument)docStore.GetDocumentById(sDocId);
				cacheStoreProvider.removeCache(baseDoc);
			}*/
			
			Map<String, Object> map = new HashMap<String, Object>();
			DelFileOrDir del = new DelFileOrDir();
			del.deleteDirectory(slocalBinFile);
			map.put("root", bResult);
			JSONObject object = new JSONObject(map);
			response.getWriter().write(object.toString());
		}catch (Exception e) {
			bResult = false;
			e.printStackTrace();
		}
}
	
	
	/////////////////////////////////////////////////////////////////////////////////////////////
	//删除云上的文件
	private boolean deleteFileOnCloud(final String token,final String fileName,String docId){
		boolean res = false;
		
		JsonObject o = new JsonObject();
		o.addProperty(FoxitCloudHttpKey.TOKEN, token);
		JsonObject ot = new JsonObject();
		ot.addProperty(FoxitCloudHttpKey.DOCID, docId);
		ot.addProperty(FoxitCloudHttpKey.PATH,"/" + fileName);
		JsonArray array = new JsonArray();
		array.add(ot);
		o.add(FoxitCloudHttpKey.DOCLIST, array);
		
		String url = Config.FOXIT_CLOUND_DELETE_FILE_URL_KEY;
		String result = sendPost(url,o);
		
		if(null == result){//删除失败
			//log.error("del file error!");
			res = false; 
		}else{
			res = true;
		}
		return res;
	}
	
	private String sendPost(String url, JsonObject jsonObject) {
		String readLine = "";
		HttpPost httpPost = null;
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			HttpClient httpClient = (HttpClient) HttpConnectionManager.getHttpClient();
			httpPost = HttpConnectionManager.getHttpPost(url);
			httpPost.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
			HttpResponse authResult = httpClient.execute(httpPost);
			int status = authResult.getStatusLine().getStatusCode();

			if (status == HttpStatus.SC_OK) {
				InputStreamReader reader = new InputStreamReader(authResult.getEntity().getContent());
				int flag;
				while((flag = reader.read()) != -1){
					readLine += (char)flag;
				}
				
				map = String2Map(readLine);
				Double ret =(Double)map.get(FoxitCloudHttpKey.RET);
				
				if(ret.intValue() != FoxitCloudHttpState.HTTP_SUCCESS){
					if(ret.intValue() != FoxitCloudHttpState.HTTP_SUCCESS_NOT_UPLOAD_BLOCKS){
						readLine = null;
						//log.error("request url:" + url + " error, the error code:" + ret);
					}
				}
				
			}else{
				readLine = null;
				//log.error("Http send Post error! url:" + url + " response status:" + status);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			httpPost.releaseConnection();
		}
		return readLine;
	}
	
	@SuppressWarnings("unchecked")
	private HashMap<String,Object> String2Map(String str){
		Gson gson = new Gson();
		HashMap<String, Object> map = gson.fromJson(str, HashMap.class);
		
		return map;
	}
}